<?php

namespace App\Http\Controllers\Admin;

use App\Common\Controllers\Admin\AdminController;
use App\Common\Enums\LetterStatusEnum;
use App\Common\Helpers\Functions;
use App\Common\Services\SystemApi\CenterApiService;
use App\Models\LetterModel;
use Illuminate\Http\Request;

class LetterController extends AdminController
{
    /**
     * constructor.
     */
    public function __construct()
    {
        $this->model = new LetterModel();

        parent::__construct();
    }

    /**
     * 列表预处理
     */
    public function selectPrepare(){
        $this->curdService->validAfter(function(){
            // 默认排序
            if(empty($this->curdService->requestData['order_by'])){
                $this->curdService->setOrderBy('letter_status', 'desc');
            }
        });

        $this->curdService->selectQueryBefore(function(){
            $this->curdService->customBuilder(function($builder){
                $adminUserInfo = Functions::getGlobalData('admin_user_info');
                $builder->whereRaw("target_admin_id IN ({$adminUserInfo['admin_user']['id']}, 0)");

                // 排序
                if(empty($this->curdService->requestData['order_by'])){
                    $builder->orderBy('letter_status', 'desc')
                        ->orderBy('updated_at', 'desc');
                }
            });
        });

        $this->curdService->selectQueryAfter(function(){
            $centerApiService = new CenterApiService();
            $adminUsers = $centerApiService->apiGetAdminUsers();
            $adminUserMap = array_column($adminUsers, null, 'id');

            foreach($this->curdService->responseData['list'] as $v){
                $v['source_admin'] = $adminUserMap[$v['source_admin_id']] ?? null;
                $v['target_admin'] = $adminUserMap[$v['target_admin_id']] ?? null;
            }
        });
    }

    /**
     * 详情预处理
     */
    public function readPrepare(){
        $this->curdService->findAfter(function(){
            if($this->curdService->findData['letter_status'] == LetterStatusEnum::UNREAD){
                $this->curdService->findData['letter_status'] = LetterStatusEnum::READ;
                $this->curdService->findData->save();
            }

            $centerApiService = new CenterApiService();
            $adminUsers = $centerApiService->apiGetAdminUsers();
            $adminUserMap = array_column($adminUsers, null, 'id');

            $this->curdService->findData['source_admin'] = $adminUserMap[$this->curdService->findData['source_admin_id']] ?? null;
            $this->curdService->findData['target_admin'] = $adminUserMap[$this->curdService->findData['target_admin_id']] ?? null;
        });
    }
}
